﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Web.Routing;
using PhotoGallery.Application;
using System.Web.Security;
using PhotoGallery.Core.Business;
using PhotoGallery.Infrastructure.Helpers;


namespace PhotoGallery.Modules
{
    /// <summary>
    /// 拦截是否登录
    /// </summary>
    public class LoginFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContextBase context = filterContext.HttpContext;

            Core.Business.Account account = UserSession.OnlineAccount;

            if (account == null)
            {
                var routeValueDictionary = new RouteValueDictionary
                                       {
                                            { "controller", "Account" }, // Security Controller
                                           { "action", "ReLogin" }, // Unauthorized Action
                                           { "reason", "你尚未登录系统!" }  // Put the reason here

                                       };
                filterContext.Result = new RedirectToRouteResult(routeValueDictionary);

            }

            base.OnActionExecuting(filterContext);

        }
    }

    /// <summary>
    ///  拦截普通 Get Post
    /// </summary>
    public class SecurityFilterAttribute : ActionFilterAttribute
    {

        #region  Field



        #endregion

        #region Constructor
        public SecurityFilterAttribute()
        {

        }
        #endregion

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContextBase context = filterContext.HttpContext;

            Core.Business.Account account = UserSession.OnlineAccount;

            string controllerName = ((string)filterContext.RouteData.Values["controller"]).ToLower();

            string actionName = ((string)filterContext.RouteData.Values["action"]).ToLower();


            HashSet<Operation> operations = new HashSet<Operation>();

            if (UserSession.OnlineAccountPermission == null)
            {
                foreach (var role in account.Roles)
                {
                    operations = operations.Union(role.Operations).ToHashSet();
                }
                UserSession.OnlineAccountPermission = operations;
            }
            else
            {
                operations = UserSession.OnlineAccountPermission as HashSet<Operation>;
            }

            bool isHavePermission = false;

            if (operations != null)
            {
                foreach (var f in operations)
                {
                    if (f.Controller.ToLower().Equals(controllerName) && f.Action.ToLower().Equals(actionName))
                    {
                        isHavePermission = true;
                        break;
                    }
                }
            }

            if (!isHavePermission)
            {
                var routeValueDictionary = new RouteValueDictionary
                                       {
                                           { "controller", "Home" }, // Security Controller
                                           { "action", "Index" }, // Unauthorized Action
                                           { "reason", "您没有权限!" }  // Put the reason here
                                       };

                filterContext.Result = new RedirectToRouteResult(routeValueDictionary);
            }

            base.OnActionExecuting(filterContext);

        }
    }

    /// <summary>
    /// 拦截该Json请求
    /// </summary>
    /// <param name="filterContext"></param>
    public class SecurityJsonFilterAttribute : ActionFilterAttribute
    {
        #region Constructor

        public SecurityJsonFilterAttribute()
        {

        }

        #endregion

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContextBase context = filterContext.HttpContext;

            Core.Business.Account account = UserSession.OnlineAccount;

            string controllerName = ((string)filterContext.RouteData.Values["controller"]).ToLower();

            string actionName = ((string)filterContext.RouteData.Values["action"]).ToLower();


            HashSet<Operation> operations = new HashSet<Operation>();

            if (UserSession.OnlineAccountPermission == null)
            {
                foreach (var role in account.Roles)
                {
                    operations = operations.Union(role.Operations).ToHashSet();
                }
                UserSession.OnlineAccountPermission = operations;
            }
            else
            {
                operations = UserSession.OnlineAccountPermission as HashSet<Operation>;
            }

            bool isHavePermission = false;

            if (operations != null)
            {
                foreach (var f in operations)
                {
                    if (f.Controller.ToLower().Equals(controllerName) && f.Action.ToLower().Equals(actionName))
                    {
                        isHavePermission = true;
                        break;
                    }
                }
            }

            if (!isHavePermission)
            {
                JsonResult jsonResult = new JsonResult();

                jsonResult.Data = "application/json";
                jsonResult.ContentEncoding = Encoding.UTF8;
                jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                jsonResult.Data = new { success = false, message = string.Format("您没有权限！使用控制器：{0},动作：{1},请联系管理员更新您的权限！", controllerName, actionName) };

                filterContext.Result = jsonResult; //new RedirectToRouteResult(routeValueDictionary);
            }

            base.OnActionExecuting(filterContext);
        }
    }


    /// <summary>
    /// 登录拦截器
    /// </summary>
    public class OnlineUserLoginFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HttpContextBase context = filterContext.HttpContext;

            Core.Business.Account account = UserSession.OnlineAccount;

            if (account != null)
            {
                OnlineUserBlock.Components.oluMonitor.MemberAppend(account.Id.ToString());
                FormsAuthentication.SetAuthCookie(account.Id.ToString(), false);
            }

            base.OnActionExecuted(filterContext);
        }
    }

    /// <summary>
    /// 登出 拦截器
    /// </summary>
    public class OnlineUserLogOutFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContextBase context = filterContext.HttpContext;

            Core.Business.Account account = UserSession.OnlineAccount;

            if (account != null)
            {
                OnlineUserBlock.Components.oluMonitor.MemberRemove();
                FormsAuthentication.SignOut();
            }

            base.OnActionExecuting(filterContext);
        }
    }


}
